from abc import ABC

from rest_framework import serializers

from .models import Friend, FriendRequest
from users.serializer import UserInfoSerializer
from users.models import User


class ContactInfoSerializer(serializers.ModelSerializer):
    friend = UserInfoSerializer()

    class Meta:
        model = Friend
        exclude = ['update_time', 'create_time', 'id', 'is_delete']


class SearchFriendSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["avatar", "email", "username", "gender", "id"]


class FriendRequestSerializer(serializers.Serializer):
    id = serializers.IntegerField(label="id", read_only=True)
    agree = serializers.BooleanField(label='是否同意', required=False)
    requesterId = serializers.IntegerField(label="好友Id", write_only=True)
    receiverId = serializers.IntegerField(label="接收者Id", write_only=True)
    requester = UserInfoSerializer(read_only=True)

    def create(self, validated_data):
        if validated_data['requesterId'] == validated_data['receiverId']:
            raise serializers.ValidationError('不能添加自己')
        hasRequest = FriendRequest.objects.filter(receiver_id=validated_data['receiverId'],
                                                    requester_id=validated_data['requesterId']).first()

        if hasRequest:
            hasRequest.delete()
        return FriendRequest.objects.create(receiver_id=validated_data['receiverId'],
                                            requester_id=validated_data['requesterId'])

